import React, { useState } from 'react';
import { BrowserConfig, SaveBrowserConfig } from '../main/types/browser';
import { ipcRenderer } from 'electron';

interface EditConfigModalProps {
  config?: BrowserConfig; // 编辑模式时传入配置,添加模式时为空
  onSave: (config: SaveBrowserConfig) => void;
  onCancel: () => void;
  isSaving: boolean;
  mode: 'add' | 'edit'; // 新增模式字段
}

export function EditConfigModal({ 
  config, 
  onSave, 
  onCancel, 
  isSaving,
  mode
}: EditConfigModalProps) {
  const [name, setName] = useState(config?.name || '');
  const [chromePath, setChromePath] = useState(config?.chromePath || '');
  const [userAgent, setUserAgent] = useState(config?.userAgent || '');
  const [userDataDir, setUserDataDir] = useState(config?.userDataDir || '');
  const [error, setError] = useState<string | null>(null);

  const handleGenerateUserAgent = async () => {
    try {
      const newUserAgent = await ipcRenderer.invoke('generate-user-agent');
      setUserAgent(newUserAgent);
    } catch (error) {
      setError('生成User Agent失败');
      setTimeout(() => setError(null), 3000);
    }
  };

  const handleGetDefaultUserDataDir = async () => {
    try {
      const result = await ipcRenderer.invoke('get-default-user-data-dir');
      if (result.success) {
        setUserDataDir(result.path);
      } else {
        setError(result.error || '获取默认用户数据目录失败');
        setTimeout(() => setError(null), 3000);
      }
    } catch (error) {
      setError(error instanceof Error ? error.message : '获取默认用户数据目录失败');
      setTimeout(() => setError(null), 3000);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!name.trim()) {
      setError('请输入浏览器实例名称');
      setTimeout(() => setError(null), 3000);
      return;
    }

    if (name.trim().length > 50) {
      setError('实例名称不能超过50个字符');
      setTimeout(() => setError(null), 3000);
      return;
    }

    onSave({
      id: config?.id || Date.now().toString(),
      name: name.trim(),
      chromePath: chromePath.trim() || undefined,
      userAgent: userAgent.trim() || undefined,
      userDataDir: userDataDir.trim() || undefined
    });
  };

  return (
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(0, 0, 0, 0.5)',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      zIndex: 1000
    }}>
      <div style={{
        backgroundColor: 'white',
        borderRadius: '8px',
        padding: '20px',
        width: '500px',
        maxWidth: '90%',
        maxHeight: '90%',
        overflow: 'auto',
        boxShadow: '0 4px 8px rgba(0, 0, 0, 0.2)'
      }}>
        <h2 style={{ marginTop: 0 }}>{mode === 'add' ? '添加浏览器实例' : '编辑浏览器实例'}</h2>
        
        {error && (
          <div style={{
            padding: '10px',
            marginBottom: '20px',
            backgroundColor: '#ffebee',
            color: '#c62828',
            borderRadius: '4px'
          }}>
            {error}
          </div>
        )}
        
        <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '15px' }}>
          <div>
            <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
              实例名称
            </label>
            <input
              type="text"
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="输入实例名称"
              required
              disabled={isSaving}
              style={{
                padding: '8px',
                borderRadius: '4px',
                border: '1px solid #ccc',
                width: '100%'
              }}
            />
          </div>
          
          <div>
            <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
              Chrome浏览器路径（可选）
            </label>
            <input
              type="text"
              value={chromePath}
              onChange={e => setChromePath(e.target.value)}
              placeholder="Chrome浏览器路径"
              disabled={isSaving}
              style={{
                padding: '8px',
                borderRadius: '4px',
                border: '1px solid #ccc',
                width: '100%'
              }}
            />
          </div>

          <div>
            <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
              用户数据目录（可选）
            </label>
            <div style={{ display: 'flex', gap: '10px' }}>
              <input
                type="text"
                value={userDataDir}
                onChange={e => setUserDataDir(e.target.value)}
                placeholder="用户数据目录"
                disabled={isSaving}
                style={{
                  padding: '8px',
                  borderRadius: '4px',
                  border: '1px solid #ccc',
                  flex: 1
                }}
              />
              <button
                type="button"
                onClick={handleGetDefaultUserDataDir}
                disabled={isSaving}
                style={{
                  backgroundColor: '#4caf50',
                  color: 'white',
                  border: 'none',
                  padding: '8px 16px',
                  borderRadius: '4px',
                  cursor: isSaving ? 'not-allowed' : 'pointer',
                  opacity: isSaving ? 0.7 : 1,
                  whiteSpace: 'nowrap'
                }}
              >
                获取默认目录
              </button>
            </div>
          </div>

          <div>
            <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
              User Agent（可选）
            </label>
            <div style={{ display: 'flex', gap: '10px' }}>
              <input
                type="text"
                value={userAgent}
                onChange={e => setUserAgent(e.target.value)}
                placeholder="User Agent"
                disabled={isSaving}
                style={{
                  padding: '8px',
                  borderRadius: '4px',
                  border: '1px solid #ccc',
                  flex: 1
                }}
              />
              <button
                type="button"
                onClick={handleGenerateUserAgent}
                disabled={isSaving}
                style={{
                  backgroundColor: '#4caf50',
                  color: 'white',
                  border: 'none',
                  padding: '8px 16px',
                  borderRadius: '4px',
                  cursor: isSaving ? 'not-allowed' : 'pointer',
                  opacity: isSaving ? 0.7 : 1,
                  whiteSpace: 'nowrap'
                }}
              >
                随机生成
              </button>
            </div>
          </div>

          <div style={{ display: 'flex', gap: '10px', marginTop: '10px' }}>
            <button
              type="submit"
              disabled={isSaving}
              style={{
                backgroundColor: '#1976d2',
                color: 'white',
                border: 'none',
                padding: '8px 16px',
                borderRadius: '4px',
                cursor: isSaving ? 'not-allowed' : 'pointer',
                opacity: isSaving ? 0.7 : 1,
                flex: 1
              }}
            >
              {isSaving ? '保存中...' : (mode === 'add' ? '添加' : '保存')}
            </button>
            <button
              type="button"
              onClick={onCancel}
              disabled={isSaving}
              style={{
                backgroundColor: '#757575',
                color: 'white',
                border: 'none',
                padding: '8px 16px',
                borderRadius: '4px',
                cursor: isSaving ? 'not-allowed' : 'pointer',
                opacity: isSaving ? 0.7 : 1,
                flex: 1
              }}
            >
              取消
            </button>
          </div>
        </form>
      </div>
    </div>
  );
} 